package com.whu.exp1jsp.controller;

import com.whu.exp1jsp.dao.CartDAO;
import com.whu.exp1jsp.dao.ProductDAO;
import com.whu.exp1jsp.dao.PurchaseDAO;
import com.whu.exp1jsp.pojo.ProductSt;
import com.whu.exp1jsp.pojo.UserSt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "myServlet", value = "/my-servlet")
public class MyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setAttribute("mode", 1);

        HttpSession session = request.getSession();
        UserSt user = session.getAttribute("user") == null ? null : (UserSt) session.getAttribute("user");

        if (user == null){
            request.setAttribute("error", "请先登录");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        ProductDAO productDAO = new ProductDAO();
        List<ProductSt> publishedProducts = null;
        try {
            publishedProducts = productDAO.selectProductsByOwnerId(user.getUserId());
        } catch (SQLException e) {
            request.setAttribute("errorMessage", "获取已发布物品失败");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        session.setAttribute("publishedProducts", publishedProducts);

        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
}
